<?php

namespace App\Models\Recognize;

use App\Models\BaseModel;

class RecognizeFoodProduceLicenseResult extends BaseModel
{
    protected $table = 'recognize_food_produce_license_results';

    protected $fillable = ['url'];

    public static function add(string $urlPath, array $recognizeResult): RecognizeFoodProduceLicenseResult
    {
        $m = static::firstOrNew(
            [
                'url' => $urlPath,
            ]
        );
        $m->producerName        = mb_substr($recognizeResult['producerName'], 0, 50);
        $m->creditCode          = mb_substr($recognizeResult['creditCode'], 0, 50);
        $m->legalRepresentative = mb_substr($recognizeResult['legalRepresentative'], 0, 50);
        $m->officeAddress       = mb_substr($recognizeResult['officeAddress'], 0, 255);
        $m->productionAddress   = mb_substr($recognizeResult['productionAddress'], 0, 255);
        $m->foodType            = mb_substr($recognizeResult['foodType'], 0, 50);
        $m->licenceNumber       = mb_substr($recognizeResult['licenceNumber'], 0, 50);
        $m->regulatoryAuthority = mb_substr($recognizeResult['regulatoryAuthority'], 0, 255);
        $m->regulatoryPersonnel = mb_substr($recognizeResult['regulatoryPersonnel'], 0, 50);
        $m->reportHotline       = mb_substr($recognizeResult['reportHotline'], 0, 50);
        $m->issueAuthority      = mb_substr($recognizeResult['issueAuthority'], 0, 50);
        $m->issueOfficer        = mb_substr($recognizeResult['issueOfficer'], 0, 50);

        if (17 == strlen($recognizeResult['issueDate'])) {
            $m->issueDate = mb_substr($recognizeResult['issueDate'], 0, 4) . '-' . mb_substr($recognizeResult['issueDate'], 5, 2) . '-' . mb_substr($recognizeResult['issueDate'], 8, 2);
        }
        if (17 == strlen($recognizeResult['validToDate'])) {
            $m->validToDate = mb_substr($recognizeResult['validToDate'], 0, 4) . '-' . mb_substr($recognizeResult['validToDate'], 5, 2) . '-' . mb_substr($recognizeResult['validToDate'], 8, 2);
        }

        $m->save();
        return $m;
    }
}
